# Program that computes the sine function with fixed point.

PI: 3216 .

# prints and pops fixed point number (1024 ~= 1.0) from -9.99 to 9.99
printFixedPoint:
  $0 0 << ?
    "-" ->
    -1 *
  .

  $0 1024 / "0" + ->
  "." ->

  @'
    1024 % 10 *
    $0 1024 / "0" + ->
    $0 0 = ?
      !@
    .
  .

  "0" ->

  ^
.

# Bhaskara I's sine approximation
sin:
  1              # stack: x sign

  $1 0 << ?
    ^
    -1 *         # x *= -1
    -1           # sign = -1
  .

  ><             # stack: sign x
  2 PI * %       # x %= 2 * PI

  $0 PI > ?      # x > PI ?
    PI -         # x -= PI
    >< -1 * ><   # sign *= -1
  .

  PI $1 - *      # x *= PI - x

  $0 16 *        # 16 * x
  $1 4 *         # 4 * x
  5 PI * PI *    # 5 * PI * PI
  >< -           # 5 * PI * PI - 4 * x
  1024 /         # (5 * PI * PI - 4 * x) / 1024
  / >< ^ *       # (16 * x) / ((5 * PI * PI - 4 * x) / 1024)
.

#-----------------

PI -1 * # from

@@
  100 +

  $0 $0 sin 

  $0 2000 + 64 / 50

  @'
    $1 $1 = ? "#" ; " " . ->
    --
  .
  ^ ^

  ><

  0 "sin(" -->
  printFixedPoint

  0 ") = " -->

  printFixedPoint

  10 ->

  $0 PI 2 * >>= ?
    !@
  .
.
